var express = require('express');
var router = express.Router();
const { insertInfo, selectInfor, creatTable, isHaveTable } = require('../dataBase/api')

/* GET users listing. */
router.post('/', function (req, res, next) {
  selectInfor("test").then(response => {
    res.send(response);
  }).catch(error => {
    res.status(500).send(error);
  })
});

router.post("/save", (req, res, next) => {

  let { tableDataString, tableName } = req.body; // 假设请求体中的参数是一个包含多个账户信息的数组
  console.log("tableName", tableName)
  let tableDataArray = JSON.parse(tableDataString)
  console.log(tableDataArray[0])
  tableData = tableDataArray.map((item) => {
    const { key, ...rest } = item
    return rest
  })
  console.log(tableData[0])
  let values = tableData.map(item => Object.values(item)); // 将账户信息映射为数组
  console.log("values", values)
  let tableKeys = Object.keys(tableData[0])
  console.log("tableKeys", tableKeys)


  isHaveTable(tableName).then((response) => {
    console.log("response", response.msg)
    if (response.isHave) {
      insertInfo(tableName, tableKeys, values).then((response2) => {
        console.log("response2", response2.msg)
        res.send({ success: true, msg: "保存成功！" })
      }).catch((error) => {
        res.send({ success: false, msg: "保存失败！", error: error })
      })
    } else {
      creatTable(tableName, tableKeys).then((result) => {
        console.log(result)
        insertInfo(tableName, tableKeys, values).then((response1) => {
          console.log("response1", response1.msg)
          res.send({ success: true, msg: "保存成功！" })
        }).catch(() => {
          res.send({ success: false, msg: "保存失败！", error: error })
        })
      }
      ).catch((creatError) => {
        res.send({ success: false, msg: "创建表失败！", error: creatError })
      })
    }
  }).catch((isHaveErr) => {
    console.log("isHaveErr", isHaveErr)
  })
});

/* GET users listing. */
router.post('/data', function (req, res, next) {
  selectInfor("weather1").then(response => {
    res.send(response);
  }).catch(error => {
    res.status(500).send(error);
  })
});

module.exports = router;
